import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gold/model/address_model.dart';
import 'package:gold/model/goods_detail_model.dart';
import 'package:gold/ui/home/invest/gold_invest_order_viewmodel.dart';
import 'package:gold/widgets/dialog/pickup_coupon_dialog.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:provider/provider.dart';
import 'package:gold/base/provider_scaffold.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description: 商品-订单页面
/// @author tangzhentao
/// @created at 20:01 2024/11/30

class GoldInvestOrderPage extends StatelessWidget {
  /// 商品信息
  final GoodsDetailModel goods;

  const GoldInvestOrderPage({required this.goods, super.key});

  @override
  Widget build(BuildContext context) {
    return ProviderScaffold<GoldInvestOrderViewmodel>(
      appBar: (_) => xfgAppbar(title: '确认订单'),
      model: GoldInvestOrderViewmodel(goods),
      builder: (ctx, order) {
        final goods = order.goods;
        final limit = goods.limit?? 0;
        final prices = goods.price?.toStringAsFixed(2).split(('.'));
        return Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(XfgSize().size10),
                child: Column(
                  children: [
                    /// 地址
                    Builder(builder: (ctx) {
                      final address = ctx.select<GoldInvestOrderViewmodel, AddressModel?>((k) => k.address);
                      final Widget child;
                      if (address != null) {
                        child = Row(
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Image.asset(Res.imagesAddress, width: XfgSize().size18, height: XfgSize().size20),
                                      SizedBox(width: XfgSize().size8),
                                      XfgText(address.name?? '', fontSize: XfgSize().text18, color: XfgColor.text1),
                                      SizedBox(width: XfgSize().size6),
                                      XfgText(address.phone?? '', fontSize: XfgSize().text16, color: XfgColor.text1),
                                    ],
                                  ),
                                  SizedBox(height: XfgSize().size6),
                                  XfgText('${address.address?? ''}${address.houseNumber?? ''}', fontSize: XfgSize().text14, color: XfgColor.text3),
                                ],
                              ),
                            ),
                            Container(
                              height: XfgSize().size40,
                              width: XfgSize().size100,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(border: Border.all(color: XfgColor.text2, width: XfgSize().size0_5), borderRadius: BorderRadius.circular(XfgSize().size40)),
                              child: XfgText('修改', color: XfgColor.text1, fontSize: XfgSize().text18),
                            )
                          ],
                        );
                      } else {
                        child = Row(
                          children: [
                            Image.asset(Res.imagesAddress, width: XfgSize().size18, height: XfgSize().size20),
                            SizedBox(width: XfgSize().size6),
                            XfgText('请选择收货地址', fontSize: XfgSize().text18, color: XfgColor.text3),
                            const Spacer(),
                            Image.asset(Res.imagesArrowRight, width: XfgSize().size10, height: XfgSize().size15)
                          ],
                        );
                      }
                      return Ink(
                        decoration: white6Decoration,
                        child: InkWell(
                          onTap: order.pickAddress,
                          borderRadius: BorderRadius.circular(XfgSize().size6),
                          child: Container(
                            padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size15, XfgSize().size20, XfgSize().size15),
                            child: child,
                          ),
                        ),
                      );
                    }),
                    /// 商品信息
                    Container(
                      margin: EdgeInsets.symmetric(vertical: XfgSize().size10),
                      padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size16, XfgSize().size10, XfgSize().size10),
                      decoration: white6Decoration,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          XfgText('  ${goods.shop?.name}', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.w500),
                          SizedBox(height: XfgSize().size10),
                          Row(
                            children: [
                              HttpImage(goods.coverImage?? '', size: Size.square(XfgSize().size100), radius: BorderRadius.circular(XfgSize().size4)),
                              SizedBox(width: XfgSize().size12),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Row(
                                      children: [
                                        XfgText(goods.name?? '', fontSize: XfgSize().text16, color: XfgColor.text2),
                                        SizedBox(width: XfgSize().size14),
                                        Container(
                                          height: XfgSize().size18,
                                          width: XfgSize().size12 + boundingTextSize('不支持七天无理由', style: TextStyle(fontSize: XfgSize().text12)).width,
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              border: Border.all(color: XfgColor.itemIntegration, width: XfgSize().size0_5),
                                              borderRadius: BorderRadius.circular(XfgSize().size2)
                                          ),
                                          child: XfgText('不支持七天无理由', fontSize: XfgSize().text12, color: XfgColor.itemIntegration),
                                        )
                                      ],
                                    ),
                                    SizedBox(height: XfgSize().size6),
                                    XfgText('单价：', fontSize: XfgSize().text16, color: XfgColor.text2, children: [
                                      TextSpan(text: '¥ ', style: TextStyle(fontSize: XfgSize().text10, color: XfgColor.itemMoney, fontWeight: FontWeight.bold)),
                                      TextSpan(text: '${prices?.first?? '0'}.', style: TextStyle(fontSize: XfgSize().text20, color: XfgColor.itemMoney, fontWeight: FontWeight.w500)),
                                      TextSpan(text: prices?.last?? '00', style: TextStyle(fontSize: XfgSize().text10, color: XfgColor.itemMoney, fontWeight: FontWeight.w500)),
                                    ]),
                                    SizedBox(height: XfgSize().size6),
                                    XfgText('库存(件)：', fontSize: XfgSize().text16, color: XfgColor.text2, children: [
                                      TextSpan(text: goods.stock?.toString()?? '--', style: TextStyle(fontSize: XfgSize().text16, color: XfgColor.text3)),
                                    ]),
                                  ],
                                ),
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                    /// 商品选购信息
                    Container(
                      margin: EdgeInsets.only(top: XfgSize().size10),
                      decoration: white6Decoration,
                      child: Column(
                        children: [
                          Builder(builder: (ctx) {
                            final number = ctx.select<GoldInvestOrderViewmodel, int>((value) => value.number);
                            return Container(
                              height: XfgSize().size56 + XfgSize().size0_5,
                              padding: EdgeInsets.only(left: XfgSize().size16),
                              decoration: BoxDecoration(border: Border(bottom: BorderSide(width: XfgSize().size0_5, color: XfgColor.colorE))),
                              child: Row(
                                children: [
                                  XfgText('数量', fontSize: XfgSize().text16, color: XfgColor.text1),
                                  const Spacer(),
                                  XfgText(limit > 0 ? '限购$limit件':'不限购', fontSize: XfgSize().text14, color: XfgColor.theme),
                                  SizedBox(width: XfgSize().size10),
                                  IconButton(
                                    onPressed: number > 1 ? () => order.number--:null,
                                    icon: Icon(CupertinoIcons.minus, size: XfgSize().size16, color: XfgColor.text3),
                                  ),
                                  Container(
                                    height: XfgSize().size22,
                                    width: XfgSize().size34,
                                    color: XfgColor.colorE,
                                    alignment: Alignment.center,
                                    child: XfgText(number.toString(),
                                        fontSize: XfgSize().text16, color: XfgColor.text2),
                                  ),
                                  IconButton(
                                    onPressed: ((limit <= 0 && number < (order.goods.stock?? 0)) || number < limit) ?  () => order.number++:null,
                                    icon: Icon(CupertinoIcons.plus, size: XfgSize().size16, color: XfgColor.text1),
                                  )
                                ],
                              ),
                            );
                          }),
                          _itemWidget1('运费', goods.freight == 0 ? '免邮':"${goods.freight}元", (goods.freight?? 0) > 0, bottom: true, showArrow: false),
                          Builder(builder: (con) {
                            final pick = con.select<GoldInvestOrderViewmodel, CouponPick?>((k) => k.coupon);
                            final showDeduction = con.select<GoldInvestOrderViewmodel, bool>((k) => k.showDeduction);
                            return GestureDetector(
                              onTap: order.pickupCoupon,
                              child: _itemWidget1('店铺优惠券',
                                  pick != null ? (pick.noCoupon ? '无可用优惠券':'满${pick.coupon.minAmount}减${pick.coupon.discountAmount?? 0}'):'请选择优惠券',
                                  pick != null && !pick.noCoupon,
                                  bottom: showDeduction),
                            );
                          }),
                          Builder(builder: (con) {
                            final showDeduction = con.select<GoldInvestOrderViewmodel, bool>((k) => k.showDeduction);
                            final pointNumber = con.select<GoldInvestOrderViewmodel, int>((k) => k.pointNumber);
                            final balanceNumber = con.select<GoldInvestOrderViewmodel, double>((k) => k.balanceNumber);
                            String valueDesc = '请选择抵扣';
                            bool hasValue = false;
                            if (pointNumber > 0 || balanceNumber > 0) {
                              hasValue = true;
                              valueDesc = '';
                              if (pointNumber > 0) {
                                valueDesc = '$pointNumber积分抵$pointNumber元';
                              }
                              if (balanceNumber > 0) {
                                valueDesc = '$valueDesc${valueDesc.isNotEmpty ? '  ':''}余额抵¥${balanceNumber.toStringAsFixed(2)}';
                              }
                            }
                            return Visibility(
                              visible: showDeduction,
                              child: GestureDetector(
                                onTap: order.pickupDeduction,
                                child: _itemWidget1('抵扣', valueDesc, hasValue),
                              ),
                            );
                          })
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(bottom: XfgSize().size10, left: XfgSize().size10),
              alignment: Alignment.centerLeft,
              child: XfgText('*因黄金物品的特殊性，暂不支持七天无理由退货', fontSize: XfgSize().text14, color: XfgColor.itemMoney),
            ),
            /// 支付按钮
            Builder(builder: (con) {
              final number = con.select<GoldInvestOrderViewmodel, int>((k) => k.number);
              final pay = con.select<GoldInvestOrderViewmodel, double>((k) => k.payAmount);
              final deduction = con.select<GoldInvestOrderViewmodel, double>((k) => k.deduction);
              return Container(
                color: XfgColor.white,
                padding: EdgeInsets.only(bottom: XfgSize().bottomBarHeight),
                child: Padding(
                  padding: EdgeInsets.fromLTRB(XfgSize().size20, XfgSize().size18, XfgSize().size10, XfgSize().size18),
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            XfgText('共$number件 ', color: XfgColor.text3, fontSize: XfgSize().text16, children: [
                              TextSpan(text: '合计', style: TextStyle(fontSize: XfgSize().text16, color: XfgColor.text1)),
                              TextSpan(text: ' ¥', style: TextStyle(fontSize: XfgSize().text12, color: XfgColor.theme)),
                              TextSpan(text: pay.toStringAsFixed(2), style: TextStyle(fontSize: XfgSize().text20, color: XfgColor.theme, fontWeight: FontWeight.bold))
                            ]),
                            XfgText('共1件 ', color: XfgColor.transparent, fontSize: XfgSize().text16, children: [
                              TextSpan(text: '已减', style: TextStyle(fontSize: XfgSize().text12, color: XfgColor.theme)),
                              TextSpan(text: ' ¥', style: TextStyle(fontSize: XfgSize().text12, color: XfgColor.theme)),
                              TextSpan(text: deduction.toStringAsFixed(2), style: TextStyle(fontSize: XfgSize().text16, color: XfgColor.theme, fontWeight: FontWeight.bold)),
                            ]),
                          ],
                        ),

                      ),
                      TextButton(
                        onPressed: order.payNow,
                        style: ButtonStyle(
                            backgroundColor: const WidgetStatePropertyAll(XfgColor.theme),
                            shape: WidgetStatePropertyAll(RoundedRectangleBorder(borderRadius: BorderRadius.circular(XfgSize().size4))),
                            fixedSize: WidgetStatePropertyAll(Size(XfgSize().size166, XfgSize().size50))
                        ),
                        child: XfgText('立即支付', fontSize: XfgSize().text16, color: XfgColor.white, bold: FontWeight.w500),
                      )
                    ],
                  ),
                ),
              );
            })
          ],
        );
      },
    );
  }

  /// 通用布局1
  Widget _itemWidget1(String text, String subText, bool hasValue, {bool bottom = false, bool showArrow = true}) => Container(
    height: XfgSize().size56 + (bottom ? XfgSize().size0_5:0),
    padding: EdgeInsets.only(left: XfgSize().size16, right: XfgSize().size10),
    decoration: bottom ? BoxDecoration(border: Border(bottom: BorderSide(width: XfgSize().size0_5, color: XfgColor.colorE))):null,
    child: Row(
      children: [
        XfgText(text, fontSize: XfgSize().text16, color: XfgColor.text1),
        Expanded(child: XfgText(subText, fontSize: XfgSize().text16, color: hasValue ? XfgColor.theme:XfgColor.text3, textAlign: TextAlign.end)),
        SizedBox(width: XfgSize().size10),
        Visibility(
          visible: showArrow,
          child: Image.asset(Res.imagesArrowRight, width: XfgSize().size10, height: XfgSize().size15, color: XfgColor.text2),
        )
      ],
    ),
  );
}
